var express = require('express');
var router = express.Router();
var soap = require('soap');
var env = require('dotenv').config();
var oauthServer = require('oauth2-server');

/**
 * oauth server
 * @type {[type]}
 */
var oauth = oauthServer({
  model: require('../oauth/model'),
  grants: ['password', 'refresh_token'],
  debug: true
});

/* GET home page. */
router.get('/', function(req, res, next) {
  res.render('index', { title: 'Express' });
});

router.get('/articles', function getArticleList(req, res, next) {
  var columnId = req.query.column_id || 8;
  var page     = req.query.page || 1;
  var perPage  = req.query.per_page || 5;

  var args = {
      'strOperType': columnId,
      'CurrentPageIndex': page,
      'PageSize': perPage,
  };

  soap.createClient(env.WSDL_URL, function(err, client) {
    client.Web_GetArticleList(args, function(err, result) {
      res.setHeader('Content-Type', 'application/json');

      res.send(result.Web_GetArticleListResult);
    });
  });
});

router.post('/oauth/access_token', oauth.grant());

// router.get('/public', function(req, res) {
//   res.send('public');
// });

// router.get('/secret', oauth.authorise(), function(req, res) {
//   res.end('secret area');
// });

// oauth error handler
router.use(oauth.errorHandler());

module.exports = router;
